<template>
  <bc-container>
    <data-panel ref="dataPanelRef" :columns="columns" :dataSource="tableData" :otherQuery="otherQuery">
      <template #toolbar>
        <el-button type="primary" @click="handleImport"> 导入 </el-button>
        <el-button type="primary" @click="handleDown"> 导出 </el-button>
        <el-button type="primary" @click="handleTransfer"> 转移 </el-button>
      </template>
      <template #action="{ scope }">
        <div class="handle-box">
          <el-button link type="primary" @click="handleGarage(scope.row)"> 车位 </el-button>
          <el-button link type="primary" @click="handleEditOrDetail('edit', scope.row)"> 编辑 </el-button>
          <el-button link type="primary" @click="handleListing(scope.row)">
            {{ scope.row.status ? '禁用' : '启用' }}
          </el-button>
          <el-button link type="primary" @click="handlePrize(scope.row)"> 送券 </el-button>
          <el-button link type="primary" @click="handleDel(scope.row)"> 删除 </el-button>
          <el-button link type="primary" @click="handleShare(scope.row)"> 浏览记录 </el-button>
        </div>
      </template>
    </data-panel>
  </bc-container>
  <bc-modal :size="[650, 160]" type="dialog" :title="formTitle()" v-model="dialogVisible" footer>
    <el-form ref="ruleFormRef" label-position="right" :model="formData" label-width="auto">
      <bc-form
        ref="bcFormRef"
        :border="false"
        padding="0"
        :fields="formOptions"
        :cols="2"
        :mode="mode"
        @change="handleChange"
      >
      </bc-form>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </bc-modal>
  <!-- 导入弹窗 -->
  <import-dialog ref="importDialogRef" @change="loadData" />
  <prize-dialog ref="prizeDialogRef" @change="loadData" />
  <!-- 转移弹窗 -->
  <transfer-dialog ref="transferDialogRef" @change="loadData" />
</template>

<script setup>
import DataPanel from '@/components/DataPanel.vue'
import BcModal from '@/components/BcModal.vue'
import BcForm from '@/components/bcForm/Index.vue'
import ImportDialog from './ImportDialog.vue'
import PrizeDialog from './PrizeDialog.vue'
import TransferDialog from './TransferDialog.vue'
import { formOptions, columns } from './config'
import { nextTick } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
import { useUserStore } from '@/store/user'
const userStore = useUserStore()

const otherQuery = reactive({
  communityId: userStore.communityId,
})
watch(
  () => userStore.communityId,
  () => {
    otherQuery.communityId = userStore.communityId
  }
)

// ============== 导入相关 ==============
const importDialogRef = ref(null)
const handleImport = async () => {
  await nextTick()
  importDialogRef.value.open(userStore.communityId)
}

/**
 * 列表
 */
const dataPanelRef = ref()
const tableData = async (params, other) => {
  params = {
    ...params,
    ...other,
  }
  const res = await $request.post('/api-parking/parking/owner/list', { params })
  return res
}
const loadData = () => {
  nextTick(() => {
    dataPanelRef.value.load()
  })
}

/**
 * 表单-线索
 */
const mode = ref('edit')
const ruleFormRef = ref()
const bcFormRef = ref()
const dialogVisible = ref(false)
const formData = reactive({})
const formTitle = () => {
  const modeMap = { add: '新增', edit: '编辑' }
  if (mode.value === 'detail') return '业主详情'
  return `${modeMap[mode.value] || ''}业主`
}
const handleChange = (val) => {
  Object.assign(formData, val.value)
}
const onClose = () => {
  dialogVisible.value = false
}
const onOpen = (val) => {
  dialogVisible.value = true
  Object.keys(formData).forEach((key) => {
    delete formData[key]
  })
  Object.assign(formData, val)
  nextTick(() => {
    bcFormRef.value.set(val)
    ruleFormRef.value.resetFields()
  })
}
// 新增
const handleAdd = () => {
  mode.value = 'add'
  onOpen({ communityId: userStore.communityId }) // 默认启用状态
}
// 编辑
const handleEditOrDetail = async (val, scope) => {
  const info = { ...scope, communityId: userStore.communityId }
  mode.value = val
  onOpen(info)
}
// 提交
const handleSubmit = async () => {
  try {
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        const params = { ...formData }
        await $request.post(
          mode.value === 'add' ? '/api-parking/parking/owner/add' : '/api-parking/parking/owner/update',
          { params }
        )
        onClose()
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        // 刷新表单
        loadData()
      }
      return false
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

// ---- 下载 ----
const handleDown = async () => {
  const res = await $request.get(`/api-parking/parking/owner/export/${userStore.communityId}`, { responseType: 'blob' })
  const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', `业主信息-${new Date().toLocaleDateString()}.xlsx`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
  ElMessage({
    type: 'success',
    message: '下载成功',
  })
}

// ============== 线索转移相关 ==============
const transferDialogRef = shallowRef()
const handleTransfer = async () => {
  await nextTick()
  transferDialogRef.value.open({ communityId: userStore.communityId })
}

// ---- 车位 ----
const handleGarage = (scope) => {
  router.push(`/owner-parking/${scope.id}`)
}

// ---- 浏览记录 ----
const handleShare = (scope) => {
  router.push(`/owner-share/${scope.id}`)
}

// ---- 送券 ----
const prizeDialogRef = ref(null)
const handlePrize = (scope) => {
  console.log('scope', scope)
  prizeDialogRef.value.open({ ownerId: scope.id, communityId: scope.communityId })
}

// ---- 启用/禁用 ----
const handleListing = (info) => {
  const { id, status } = info
  ElMessageBox.confirm(`是否${status ? '禁用' : '启用'}该用户?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 执行删除操作
      await $request.get(`/api-parking/parking/owner/status/${id}/${status ? 0 : 1}`)
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
      // 刷新表单
      loadData()
    })
    .catch(() => {
      // 显示取消消息
    })
}

//  ---- 删除 ----
const handleDel = (info) => {
  const { id } = info
  ElMessageBox.confirm(`是否删除该业主?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 执行删除操作
      await $request.get(`/api-parking/parking/owner/delete/${id}`)
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
      // 刷新表单
      loadData()
    })
    .catch(() => {
      // 显示取消消息
    })
}
</script>

<style lang="scss" scoped></style>
